import store from '@/store'
import request from '@/utils/request.js'
// api
import { getPermission } from '@/api/config/config.js'
import { userLogin, getUserInfo } from '@/api/user'

// 获取设备信息
export function getSystemInfo() {
	uni.getSystemInfo({
		success: res => {
			const modelmes = res.model
			if (modelmes.search('iPhone X') !== -1) {
				store.commit('config/setIsPhoneX', true)
			}
		}
	})
}

// 用户登录小程序
export function startLogin() {
	const { PUserId: userId } = store.state.user.userInfo
	
	return new Promise(resolve => {
		// 已获取用户信息
		if (userId) {
			resolve()
			return
		}

		// 未获取用户信息
		uni.login({
			success: res => {
				const app = getApp()
			
				// 获取用户信息
				userLogin({
					code: res.code,
					parid: app.globalData.parentId
				}).then(res => {
					// 设置门店信息
					store.commit('config/setStoreInfo', res.Store)
					// 设置用户信息
					store.commit('user/setUserInfo', res.User)
					// 更新功能权限
					updatePermission()
					resolve()
				})
			}
		})
	})
}

// 小程序更新检测
export function checkUpdate() {
	const updateManager = uni.getUpdateManager() // 获取更新管理器对象
	updateManager.onCheckForUpdate(res => {
		if (res.hasUpdate) {
			updateManager.onUpdateReady(() => {
				uni.showModal({
					title: '更新提示',
					content: '新版本已经准备好，点击确定重新启动',
					showCancel: false,
					success: res => {
						if (res.confirm) {
							updateManager.applyUpdate() 
						}
					}
				})
			})
			updateManager.onUpdateFailed(() => {
				wx.showModal({
					title: '提示',
					content: '检查到有新版本，但是下载失败，请检查网络设置',
					showCancel: false
				})
			})
		}
	})
}

// 更新用户信息
export function updateUserInfo() {
	const { PUserId: userId } = store.state.user.userInfo
	if (userId) {
		getUserInfo().then(res => {
			// 未到账余额
			res.User.notBalance = res.OutOfAccount
			// 更新用户信息
			store.commit('user/setUserInfo', res.User)
		})
	}
}

// 更新功能权限
export function updatePermission() {
	const { PUserId: userId } = store.state.user.userInfo
	if (!userId) return
	getPermission().then(res => {
		store.commit('config/setPermission', res.data)
	})
}

// 获取用户位置信息
export function getLocation() {
	uni.getLocation({
		type: 'wgs84',
		success: res => {
			const app = getApp()
			app.globalData.longitude = res.longitude
			app.globalData.latitude = res.latitude
		}
	})
}

// 连接wifi
export function connectWifi() {
	const storeInfo = store.state.config.storeInfo
	uni.startWifi({
		success: () => {
			uni.connectWifi({
				SSID: storeInfo.FWiFiName,
				password: storeInfo.FWiFiPass,
				success: res => {
					uni.showToast({
						title: 'wifi连接成功'
					})
				},
				fail: res => {
					uni.showToast({
						title: 'wifi连接失败',
						icon: 'none'
					})
				}
			})
		}
	})
}

// 传入腾讯视频地址，返回可播放的视频高清地址
export function getVideoUrl(url) {
	let start = url.lastIndexOf('/') + 1
	let end = url.lastIndexOf('.')
	let vid = url.slice(start, end)
	
	return new Promise((resolve) => {
		uni.request({
			url: 'https://vv.video.qq.com/getinfo?vid=' + vid + '&platform=101001&charge=0&otype=json',
			method: 'get',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			success: res => {
				let json1 = JSON.parse((res.data.replace(/QZOutputJson=/, '') + 'qwe').replace(/;qwe/, ''))
				let vid = json1.vl.vi[0].vid
				let filename = vid + '.mp4'
				uni.request({
					url: 'https://vv.video.qq.com/getkey?format=2&otype=json&vt=150&vid=' + vid + '&ran=0\%2E9477521511726081\\&charge=0&filename=' + filename + '&platform=11',
					method: 'get',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: async res => {
						let json2 = JSON.parse((res.data.replace(/QZOutputJson=/, '') + 'qwe').replace(/;qwe/, ''))
						// 高清视频地址
						if (json2.filename) {
							let urlStr1 = json1['vl']['vi'][0]['ul']['ui'][0]['url']
							let result = urlStr1 + filename + '?vkey=' + json2.key
							resolve(result)
						} else {
							// 标清视频地址
							resolve(await getVideoUrl_SD(vid))
						}
					}
				})
			}
		})
	})
}

// 传入腾讯vid，返回可播放的视频标清地址
export function getVideoUrl_SD(vid) {
	return new Promise((resolve) => {
		uni.request({
			url: 'https://vv.video.qq.com/getinfo?vid=' + vid + '&platform=101001&charge=0&otype=json',
			method: 'get',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			success: function(res) {
				let dataJson = res.data.replace(/QZOutputJson=/, '') + 'qwe'
				let dataJson1 = dataJson.replace(/;qwe/, '')
				let data = JSON.parse(dataJson1)
				let url = data.vl.vi[0].ul.ui[0].url
				let start = url.lastIndexOf('/', url.length - 2)
				let end = url.lastIndexOf('/') + 1
				let str = url.slice(start, end)
				url = 'http://ugcws.video.gtimg.com' + str
				let url2 = url.replace(/http/, 'https')
				let fu = data.vl.vi[0].fn
				let fvkey = data.vl.vi[0].fvkey
				let result = url2 + fu + '?vkey=' + fvkey
				resolve(result)
			}
		})
	})
}
